package com.ktdaddy.controller.system;

import com.ktdaddy.request.LoginReq;
import com.ktdaddy.request.PwdChangeReq;
import com.ktdaddy.service.PassportService;
import com.ktdaddy.utils.ApiResponse;
import com.ktdaddy.utils.JwtUtils;
import com.ktdaddy.response.LoginResultResp;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author kdaddy@163.com
 * @date 2021/4/29 22:01
 * 权限认证相关接口
 */
@RequestMapping("/whale/system/passport")
@RestController
public class PassportController {

    @Autowired
    private PassportService passportService;


    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @PostMapping("/login")
    public ApiResponse login(@RequestBody LoginReq loginBO, HttpServletResponse response) {
        LoginResultResp result = passportService.login(loginBO);

        if(result.getResult()){
            //若登录成功，签发 JWT token
            String jwtToken = JwtUtils.sign(loginBO.getKernelName(), JwtUtils.SECRET);
            //将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
            result.setToken(jwtToken);
            response.setHeader(JwtUtils.AUTH_HEADER,jwtToken);
        }
        return ApiResponse.ok(result);
    }

    @ApiOperation(value = "修改密码",notes = "修改密码",httpMethod = "POST")
    @PostMapping("/changePwd")
    public ApiResponse changePwd(@RequestBody PwdChangeReq pwdChangeReq){
        passportService.changePwd(pwdChangeReq);
        return ApiResponse.ok();
    }

    @ApiOperation(value = "用户登出",notes = "用户登出",httpMethod = "GET")
    @GetMapping("/logout")
    private ApiResponse logout(){
        passportService.logout();
        return ApiResponse.ok();
    }
}
